const { logger } = require('../utils/logger');

const errorHandler = (err, req, res, next) => {
  logger.error(`请求处理错误: ${err.message}`, {
    stack: err.stack,
    url: req.url,
    method: req.method,
    ip: req.ip,
    userAgent: req.get('User-Agent'),
    body: req.body,
    query: req.query,
    headers: {
      'content-type': req.get('Content-Type'),
      'accept': req.get('Accept')
    }
  });

  // 浏览器相关错误
  if (err.message.includes('Browser') || err.message.includes('Page')) {
    return res.status(503).json({
      success: false,
      error: '浏览器服务暂时不可用，请稍后重试',
      code: 'BROWSER_ERROR'
    });
  }

  // 超时错误
  if (err.message.includes('timeout') || err.code === 'ETIMEDOUT') {
    return res.status(408).json({
      success: false,
      error: '请求超时，请稍后重试',
      code: 'TIMEOUT_ERROR'
    });
  }

  // 验证错误
  if (err.type === 'validation') {
    return res.status(400).json({
      success: false,
      error: err.message,
      code: 'VALIDATION_ERROR'
    });
  }

  // 默认服务器错误
  res.status(500).json({
    success: false,
    error: '服务器内部错误',
    code: 'INTERNAL_ERROR'
  });
};

module.exports = errorHandler;
